use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

/// Converts input Chinese characters to Wade-Giles romanization.
/// Handles both simplified and traditional characters using separate HashMaps.
pub fn converter(input: &str) -> String {
    let (simplified_map, traditional_map) = load_mappings("src/spell.csv");
    let mut result = String::new();

    for c in input.chars() {
        if c.is_ascii() {
            // 忽略ASCII字符
            continue;
        }
        if let Some(pinyin) = simplified_map.get(&c).or_else(|| traditional_map.get(&c)) {
            result.push_str(pinyin);
            result.push(' ');
        } else {
            // 保留原字符
            result.push(c);
            result.push(' ');
        }
    }

    let trimmed = result.trim_end().to_string();
    capitalize_first_letter(trimmed)
}

/// Capitalizes the first letter of the input string.
fn capitalize_first_letter(s: String) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

/// Loads simplified and traditional mappings from the CSV file.
/// Assumes the CSV has the following columns:
/// 1. Simplified Chinese character
/// 2. Traditional Chinese character
/// 3. Wade-Giles pinyin
fn load_mappings(file_path: &str) -> (HashMap<char, String>, HashMap<char, String>) {
    let file = File::open(file_path).expect("无法打开spell.csv文件");
    let reader = BufReader::new(file);
    let mut simplified_map = HashMap::new();
    let mut traditional_map = HashMap::new();

    for line in reader.lines() {
        if let Ok(l) = line {
            let parts: Vec<&str> = l.split(',').collect();
            if parts.len() >= 3 {
                let simplified_char = parts[0].trim().chars().next().unwrap_or(' ');
                let traditional_char = parts[1].trim().chars().next().unwrap_or(' ');
                let pinyin = parts[2].trim().to_string();

                // 插入简体字到拼音的映射
                if simplified_char != ' ' {
                    simplified_map.insert(simplified_char, pinyin.clone());
                }

                // 插入繁体字到拼音的映射
                if traditional_char != ' ' {
                    traditional_map.insert(traditional_char, pinyin);
                }
            }
        }
    }

    (simplified_map, traditional_map)
}

